/**
 * 
 */
package com.crystal.jcms.frament;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;

import com.crystal.constant.Constant;
import com.crystal.jcms.shpz.ActivityAbount;
import com.crystal.jcms.shpz.ActivityFrame;
import com.crystal.jcms.shpz.ActivityLogin;
import com.crystal.jcms.shpz.R;
import com.crystal.jcms.utils.DataCleanManager;
import com.crystal.jcms.utils.ShowMsgUtils;
import com.crystal.jcms.utils.SpUtils;

import android.R.menu;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 
 *
 * @author Lean @date:2014-8-4
 */
public class SetFragment extends BaseFragment {
	private static final int PICK_FROM_CAMERA = 1;
	private static final int CROP_FROM_CAMERA = 2;
	private static final int PICK_FROM_FILE = 3;
	private Uri imgUri;
	private String filePath = Environment.getExternalStorageDirectory() + "/crop_head.png";

	private MenuPopup menuPopup;
	private ImageView imgPhoto;
	private TextView txtUserName, txtUserId;
	private Button btnAbount, btnClear, btnLoginOut;

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);

	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.content_set, container, false);
		txtUserName = (TextView) view.findViewById(R.id.txtUserName);
		txtUserId = (TextView) view.findViewById(R.id.txtUserId);
		imgPhoto = (ImageView) view.findViewById(R.id.imgPhoto);
		btnAbount = (Button) view.findViewById(R.id.btnAbount);
		btnClear = (Button) view.findViewById(R.id.btnClear);
		btnLoginOut = (Button) view.findViewById(R.id.btnLoginOut);
		initData();
		return view;
	}

	public void initData() {
		if (!SpUtils.get(mContext, "UserName", "").equals("")) {
			txtUserName.setText(SpUtils.get(mContext, "UserName", "").toString());
			txtUserId.setText("账号：" + SpUtils.get(mContext, "UserId", "").toString());
		}
		File file = new File(filePath);
		if (file.exists()) {
			Bitmap bitmap = BitmapFactory.decodeFile(filePath);
			imgPhoto.setImageBitmap(bitmap);
		}
		imgPhoto.setOnClickListener(new imgViewOnClick());
		btnAbount.setOnClickListener(new btnAbountOnClick());
		btnClear.setOnClickListener(new btnClearOnClick());
		btnLoginOut.setOnClickListener(new btnLoginOutOnClick());
	}

	// 关于我们
	public class btnAbountOnClick implements OnClickListener {
		@Override
		public void onClick(View v) {
			Intent intent = new Intent(mContext, ActivityAbount.class);
			startActivity(intent);
		}
	}

	// 清空缓存
	public class btnClearOnClick implements OnClickListener {
		@Override
		public void onClick(View v) {
			DataCleanManager.clearAllCache(mContext);
			ShowMsgUtils.ShowToast(mContext, "成功清理缓存！");
		}
	}

	public class btnLoginOutOnClick implements OnClickListener {

		@Override
		public void onClick(View v) {
			AlertDialog.Builder alertBuilder = new AlertDialog.Builder(mContext);
			alertBuilder.setTitle("提示");
			alertBuilder.setMessage("确定要注销吗？");
			alertBuilder.setCancelable(false);
			alertBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					Intent intent = new Intent(getActivity(), ActivityLogin.class);
					SpUtils.put(mContext, "Password", "");
					SpUtils.put(mContext, "IsRemeber", false);
					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(intent);
					dialog.dismiss();
				}
			});
			alertBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
				}
			});
			alertBuilder.show();

		}
	}

	// 修改头像
	public class imgViewOnClick implements OnClickListener {

		@Override
		public void onClick(View v) {
			menuPopup = new MenuPopup(mContext);
			menuPopup.btnCamera.setOnClickListener(new btnCameraOnClick());
			menuPopup.btnPhoto.setOnClickListener(new btnPhotoOnClick());
			menuPopup.btnCancel.setOnClickListener(new btnCancelOnClick());
			menuPopup.showPopupWindow(v);
		}
	}

	// 拍照
	public class btnCameraOnClick implements OnClickListener {

		@Override
		public void onClick(View v) {
			Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
			imgUri = Uri.fromFile(new File(filePath));
			intent.putExtra(MediaStore.EXTRA_OUTPUT, imgUri);
			startActivityForResult(intent, PICK_FROM_CAMERA);
		}
	}

	// 从相册选择照片
	public class btnPhotoOnClick implements OnClickListener {

		@Override
		public void onClick(View v) {
			Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
			intent.setType("image/*");
			startActivityForResult(intent, PICK_FROM_FILE);
		}

	}

	// 回调
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode != mContext.RESULT_OK) {
			return;
		}
		switch (requestCode) {
		case PICK_FROM_CAMERA:
			doCrop();
			break;
		case PICK_FROM_FILE:
			imgUri = data.getData();
			doCrop();
			break;
		case CROP_FROM_CAMERA:
			if (null != data) {
				setCropImg(data);
			}
			break;
		}
	}

	/**
	 * set the bitmap
	 * 
	 * @param picdata
	 */
	private void setCropImg(Intent picdata) {
		Bundle bundle = picdata.getExtras();
		if (null != bundle) {
			Bitmap mBitmap = bundle.getParcelable("data");
			imgPhoto.setImageBitmap(mBitmap);
			saveBitmap(filePath, mBitmap);
		}
	}

	/**
	 * save the crop bitmap
	 * 
	 * @param fileName
	 * @param mBitmap
	 */
	public void saveBitmap(String fileName, Bitmap mBitmap) {
		File f = new File(fileName);
		FileOutputStream fOut = null;
		try {
			f.createNewFile();
			fOut = new FileOutputStream(f);
			mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
			fOut.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				fOut.close();
				ShowMsgUtils.ShowToast(mContext, "保存成功！");
				if (menuPopup != null && menuPopup.isShowing()) {
					menuPopup.dismiss();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

	private void doCrop() {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setType("image/*");
		List<ResolveInfo> list = mContext.getPackageManager().queryIntentActivities(intent, 0);
		int size = list.size();

		if (size == 0) {
			ShowMsgUtils.ShowToast(mContext, "can't find crop app");
			return;
		} else {
			intent.setData(imgUri);
			intent.putExtra("outputX", 300);
			intent.putExtra("outputY", 300);
			intent.putExtra("aspectX", 1);
			intent.putExtra("aspectY", 1);
			intent.putExtra("scale", true);
			intent.putExtra("return-data", true);

			// only one
			if (size == 1) {
				Intent i = new Intent(intent);
				ResolveInfo res = list.get(0);
				i.setComponent(new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
				startActivityForResult(i, CROP_FROM_CAMERA);
			}
		}
	}

	// 取消
	public class btnCancelOnClick implements OnClickListener {

		@Override
		public void onClick(View v) {
			if (menuPopup != null && menuPopup.isShowing()) {
				menuPopup.dismiss();
			}
		}

	}

	@Override
	public void onResume() {
		super.onResume();
		ActivityFrame.currFagTag = Constant.STR_FRAGMENT_SET;
	}

}
